<?php
namespace app\home\controller;

use \app\common\controller\Homebase;
use \thans\Ret;
use \think\Db;
use \think\Loader;
use \think\Request;
class Menu extends Basic
{
    public function _initialize()
    {
        $this->recycleBin = Loader::model('RecycleBin');
        $this->authRule   = Loader::model('AuthRule');
        $this->menu       = Loader::model('Menu');
		$type			  = Request::instance()->param('type');
        $arr[0]['text']   = '菜单列表';
        $arr[0]['url']    = 'index';
		$arr[0]['param']   = array("type"=>$type);
        $arr[1]['text']   = '新增菜单';
        $arr[1]['url']    = 'add';
		$arr[1]['param']   = array("type"=>$type);
        $this->assign('third_menu', $arr);
    }
    /**
     * 菜单列表
     * @return [type] [description]
     */
    public function index($type=1)
    {
        if( $type == 1)
            $list = $this->menu->where(array("type"=>$type))->order('listorder ASC')->select();
        else
            $list = $this->menu->where("type","in","(0,3,2)")->order('listorder ASC')->select();
        $tree = new \thans\Common\tree($list);
        $list = $tree->formatArrayForTree('id', 'menu_pid', 'name');

        //对二维数组排序
        $menu_pids = array();
        foreach ($list as $value) {
            $menu_pids[] = $value['menu_pid'];
        }
        // array_multisort($menu_pids, SORT_ASC, $list);

        //计算数组层级
        $levelArray = array();
        foreach ($list as $value) {
            if (isset($levelArray[$value['menu_pid']])) {
                $levelArray[$value['id']] = $levelArray[$value['menu_pid']] + 1;
            } else {
                $levelArray[$value['id']] = 0;
            }
        }

        foreach ($list as $key => $value) {
            //根据对应的层级显示  模块\控制器\方法
            if (isset($levelArray[$value['id']])) {
                if ($levelArray[$value['id']] == 1) {
                    $list[$key]['model'] = $value['controller'];
                } else if ($levelArray[$value['id']] == 2) {
                    $list[$key]['model'] = $value['action'];
                }
                $list[$key]['model'] = $value['model'] . '/' . $value['controller'] . '/' . $value['action'];
            }
            $list[$key]['action'] = '<a href="' . url('add', 'id=' . $list[$key]['id']) . '"><i class="layui-icon layui-icon-edit"></i></a>&nbsp;<i class="layui-icon layui-icon-delete" action-url="' . url('del', 'id=' . $list[$key]['id']) . '" data-info="您确定要删除本菜单吗？" action="del" title="删除"></i>';
            $list[$key]['status'] = $value['status'] ? "显示" : "隐藏";
        }
        $tree->initArr($list);
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $str        = "<tr><td style='width:64px;'><input type='hidden' name='id[]' value='\$id'><input type='text' name='order[]'  class = 'form-control' style='width:60px;' value='\$listorder' class='pxinput'></td>
        <td>\$id</td>
        <td>\$spacer\$name</td>
        <td>\$model</td>
        <td>\$status</td>
        <td>\$level</td>
        <td>\$action</td></tr>";
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        return $this->fetch('index');
    }
    public function index2() {
        return $this->index(2);
    }
    public function listorder()
    {
        $res = listorder('id', input('id/a'), input('order/a'), $this->menu);
        if ($res) {
            return $this->ret->setCode(0)->setMsg('排序更新成功')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('排序更新失败')->toJson();
        }
    }

    public function add($type=1)
    {
        if (input('id')) {
            $list = $this->menu->where('id', input('id'))->find();
            $this->assign('data', $list);
            $selectid = $list['menu_pid'];
        } else {
            $selectid = 0;
        }
//        var_dump($list);
        $this->assign('menulist', $this->getOptionTree($selectid));
		$this->assign("type",$type);
        return $this->fetch();
    }
    public function edit()
    {
        if (input('id')) {
            $list = $this->menu->where('id', input('id'))->find();
            $this->assign('data', $list);
            $selectid = $list['menu_pid'];
            $this->assign('menulist', $this->getOptionTree($selectid));
            return $this->fetch();
        }
    }
    /**
     * 获取select2格式数据
     */
    public function getOptionTree($select = 0)
    {
        $list = $this->menu->select();
        $tree = $foo = new \thans\Common\tree($list);
        $tree->formatArrayForTree('id', 'menu_pid', 'name');
        $data = $tree->get_tree(0, "<option value='\$id' \$selected>\$spacer \$name </option>", $select);
        return $data;
    }
    public function go_add()
    {

        $model      = trim(strtolower(input('model')));
        $controller = trim(strtolower(input('controller')));
        $action     = trim(strtolower(input('action')));
        $data       = trim((string) input('data'));
        $status     = input('status');
        $status     = $status ? 1 : 0;
        $type       = intval(input('type'));
        $rule_value = "{$model}/{$controller}/{$action}";
        $level = input('level', 1);

        $data = array(
            'menu_pid'   => intval(input('menu_pid')),
            'name'       => trim((string) input('name')),
            'model'      => $model,
            'controller' => $controller,
            'action'     => $action,
            'data'       => $data,
            'icon'       => trim((string) input('icon')),
            'remark'     => trim((string) input('remark')),
            'rule_value' => $rule_value,
            'listorder'  => intval(input('listorder')),
            'type'       => $type,
            'option'    => trim((string) input('option')),
            'status'     => $status,
            'level'     => $level,
        );
        Db::startTrans();

        try {
            $menu_id = $this->menu->insertGetId($data);
            if (!$menu_id) {
                return $this->ret->setCode(1)->setMsg('添加失败')->toJson();
            }
            if (!$type) {
                Db::commit();
                return $this->ret->setMsg('添加成功')->setReload()->toJson();
            }
            $ruleData = array(
                'rule_module'    => $model,
                'rule_type'      => 'admin_rule',
                'rule_name'      => $rule_value,
                'rule_param'     => trim((string) input('data')),
                'rule_title'     => trim((string) input('name')),
                'rule_status'    => 1,
                'rule_condition' => '',
            );
            $rule_id = $this->authRule->insertGetId($ruleData);
            Db::commit();
            return $this->ret->setMsg('添加成功')->setData('menu_id', $menu_id)->setData('rule_id', $rule_id)->setReload()->toJson();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->ret->setCode(2)->setMsg('添加失败')->toJson();
        }
    }

    public function go_edit()
    {
        $model      = trim(strtolower(input('model')));
        $controller = trim(strtolower(input('controller')));
        $action     = trim(strtolower(input('action')));
        $data       = trim((string) input('data'));
        $status     = input('status');
        $status     = $status ? 1 : 0;
        $type       = intval(input('type'));
        $rule_value = "{$model}/{$controller}/{$action}";
        $level = input('level', 1);
        $data = array(
            'menu_pid'   => intval(input('menu_pid')),
            'name'       => trim((string) input('name')),
            'model'      => $model,
            'controller' => $controller,
            'action'     => $action,
            'data'       => $data,
            'icon'       => trim((string) input('icon')),
            'remark'     => trim((string) input('remark')),
            'option'    => trim((string) input('option')),
            'rule_value' => $rule_value,
            'type'       => $type,
            'status'     => $status,
            'level'     => $level,
        );
        if (input('listorder') != '') {
            $data['listorder'] = intval(input('listorder'));
        }
        $menu      = $this->menu->where('id', input('id'))->find();
        $menu_type = $menu['type'];
        $ruleData = array(
            'rule_module'    => $model,
            'rule_type'      => 'admin_rule',
            'rule_name'      => $rule_value,
            'rule_param'     => trim((string) input('data')),
            'rule_title'     => trim((string) input('name')),
            'rule_status'    => 1,
            'rule_condition' => '',
        );
        Db::startTrans();
        try {
            $res = $this->menu->where($data)->find();
            if ($res) {
                return $this->ret->setCode(0)->setMsg('更新成功')->toJson();
            }
            $menu_status = $this->menu->where('id', input('id'))->update($data);
            if (!$menu_status) {
                return $this->ret->setCode(1)->setMsg('更新失败')->toJson();
            }
            $ruleData = array(
                'rule_module'    => $model,
                'rule_type'      => 'admin_rule',
                'rule_name'      => $rule_value,
                'rule_param'     => trim((string) input('data')),
                'rule_title'     => trim((string) input('name')),
                'rule_status'    => 1,
                'rule_condition' => '',
            );

            //  判断之前菜单得类型
            if (!$menu_type) {
                if (!$type) {
                    Db::commit();
                    return $this->ret->setMsg('更新成功')->setReload()->toJson();
                } else {
                    $rule_id = $this->authRule->insert($ruleData);
                    Db::commit();
                    return $this->ret->setMsg('更新成功')->setData('rule_id', $rule_id)->setReload()->toJson();
                }
            } else {
                if (!$type) {
                    $auth_rule_status = $this->authRule->where(array('rule_name' => $rule_value))->delete();
                    Db::commit();
                    return $this->ret->setMsg('更新成功')->setReload()->toJson();
                } else {
                    $auth_rule_status = $this->authRule->where(array('rule_name' => $rule_value))->update($ruleData);
                    Db::commit();
                    return $this->ret->setMsg('更新成功')->setData('auth_rule_status', $auth_rule_status)->setReload()->toJson();
                }
            }
        } catch (\Exception $e) {
            throw $e;
            Db::rollback();
            return $this->ret->setCode(1)->setMsg('更新失败')->toJson();
        }
    }

    public function del()
    {

        $where      = array('id' => input('id'));
        $listObject = $this->menu->where('id', input('id'))->find();
        $list       = $listObject->toArray();

        //判断删除数据的类型为权限认证+菜单 则删除menu和authRule
        if ($list['type'] == 1) {

            $auth_map['rule_name'] = $list['data'] ? $list['model'] . '/' . $list['controller'] . '/' . $list['action'] . '/' . $list['data'] : $list['model'] . '/' . $list['controller'] . '/' . $list['action'];
            $list2                 = $this->authRule->where($auth_map)->find();

            $result = $this->recycleBin->cutout(
                $this->authRule,
                $list2,
                $auth_map
            );

            //判断删除数据的类型为仅菜单 则删除menu
        }
        $result = $this->recycleBin->cutout(
            $this->menu,
            $listObject,
            $where
        );

        if ($result) {
            return $this->ret->setMsg('删除成功')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
        }
    }
}
